package com.mapResult.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.mapResult.mapper.BusResultMapMapper;
import com.mapResult.service.BusResultMapServiceImpl;
import jdk.jfr.events.ExceptionStatisticsEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author chenming
 * @description
 * @create: 2022-11-01
 */
@RestController
public class SwitchDataSourceController {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private BusResultMapMapper busResultMapMapper;
    @Autowired
    private BusResultMapServiceImpl busResultMapService;

    @GetMapping("/getDataSource")
    public Object getDataSource(){
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        return ds.getDataSources().keySet();
    }

    @PostMapping("/addDataSource")
    public Object addDataSource(@RequestBody DataSourceProperty params) throws SQLException {
        params.setLazy(true);
        DruidDataSource newDataSource = new DruidDataSource();
        newDataSource.setDriverClassName(params.getDriverClassName());
        newDataSource.setUrl(params.getUrl());
        newDataSource.setUsername(params.getUsername());
        newDataSource.setPassword(params.getPassword());
        newDataSource.setConnectionErrorRetryAttempts(1);
        newDataSource.setBreakAfterAcquireFailure(true);
        newDataSource.setMaxWait(500);
        try {
            Connection connection = newDataSource.getConnection();
        }catch (Exception e){
            e.printStackTrace();
            return "连接失败";
        }
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.addDataSource(params.getPoolName(), newDataSource);
        return ds.getDataSources().keySet();
    }

    @GetMapping("/getResultMap")
    public Object getResultMap(String schema){
        DynamicDataSourceContextHolder.push(schema);
        return busResultMapMapper.selectUserList("bus_region_management");
    }

}
